import { getLocalHistories } from '@/utils/storage';
import { uniq } from 'lodash';

export type ResultType = {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: number;
  pubdate: string;
  cover: {
    type: number;
    images: string[];
  };
  like_count: number;
  collect_count: number;
};

const initialState = {
  suggests: [] as string[],
  histories: getLocalHistories() as string[],
  resultData: {
    page: 1,
    per_page: 10,
    results: [] as ResultType[],
    total_count: 0,
  },
};

export type ActionType =
  | { type: 'search/saveSuggests'; payload: string[] }
  | { type: 'search/saveHistories'; payload: string }
  | { type: 'search/clearHistories' }
  | { type: 'search/saveResults'; payload: typeof initialState.resultData }
  | { type: 'search/clearResults' };

export default function searchReducer(
  state = initialState,
  action: ActionType
): typeof initialState {
  switch (action.type) {
    case 'search/saveSuggests':
      return {
        ...state,

        suggests: action.payload.filter((item) => !!item),
      };

    case 'search/saveHistories':
      return {
        ...state,

        histories: uniq([action.payload, ...state.histories]),
      };
    case 'search/clearHistories':
      return {
        ...state,
        histories: [],
      };

    case 'search/saveResults':
      return {
        ...state,
        resultData: {
          ...action.payload,
          results: [...state.resultData.results, ...action.payload.results],
        },
      };
    case 'search/clearResults':
      return {
        ...state,
        resultData: {
          ...initialState.resultData,
        },
      };

    default:
      return state;
  }
}
